import Router from '@koa/router';
import sequelize from '../config/db.js';
const router = new Router({ prefix: '/api' });
// 统一的错误响应结构
const errorResponse = (code, message) => ({
  code,
  message,
  data: null
});

// 统一的成功响应结构
const successResponse = (data, meta = null) => ({
  code: 'SUCCESS',
  message: '操作成功',
  data,
  meta
});
// 点赞
router.post('/like', async (ctx) => {
  const { user_id, target_id, target_type } = ctx.request.body;

  try {
    // 使用INSERT ... ON DUPLICATE KEY UPDATE语句
    const sql = `
    INSERT INTO likes (user_id, target_id, target_type, like_status) 
    VALUES (?, ?, ?, '1') 
    ON DUPLICATE KEY UPDATE like_status = '1', updated_at = CURRENT_TIMESTAMP
    `;
    await sequelize.query(sql, {
      replacements: [user_id, target_id, target_type],
      type: sequelize.QueryTypes.INSERT // 返回结果类型为INSERT
    });

    ctx.status = 200;
    ctx.body = successResponse();
  } catch (err) {
    console.error(err);
    ctx.status = 500;
    ctx.body = errorResponse('INTERNAL_SERVER_ERROR', '操作失败');
  }
});

// 取消点赞
router.post('/unlike', async (ctx) => {
  const { user_id, target_id, target_type } = ctx.request.body;

  try {
    // 使用INSERT ... ON DUPLICATE KEY UPDATE语句
    const sql = `
    INSERT INTO likes (user_id, target_id, target_type, like_status) 
    VALUES (?, ?, ?, '1') 
    ON DUPLICATE KEY UPDATE like_status = '0', updated_at = CURRENT_TIMESTAMP
    `;
    await sequelize.query(sql, {
      replacements: [user_id, target_id, target_type],
      type: sequelize.QueryTypes.INSERT // 返回结果类型为INSERT
    });


    ctx.status = 200;
    ctx.body = successResponse();
  } catch (err) {
    console.error(err);
    ctx.status = 500;
    ctx.body = errorResponse('INTERNAL_SERVER_ERROR', '操作失败');
  }
});

router.get('/likeStatus', async (ctx) => {
  const { user_id, target_id } = ctx.request.query;
  const sql = `
  SELECT * FROM likes
  WHERE likes.target_id = :target_id
  AND likes.user_id = :user_id
  `;
  const likeStatus = await sequelize.query(sql, {
    replacements: { target_id, user_id },
    type: sequelize.QueryTypes.SELECT
  });
  if (likeStatus.length) {
    ctx.body = successResponse(likeStatus[0])
    return;
  }
  ctx.body = successResponse({})

})

export default router;